package com.jeeplus.modules.monitor.utils;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeeplus.common.config.Global;
import com.jeeplus.modules.monitor.model.ErrorMessage;
import com.jeeplus.modules.monitor.model.Message;
import com.jeeplus.modules.monitor.model.Page;


import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;


public class Achieve {

	private static String appId = Global.getConfig("appId");
	private static String appSecret = Global.getConfig("appSecret");

	private static ObjectMapper objectMapper;
	private static Logger log = Logger.getLogger(Achieve.class);
	public  static String getUrl(String type,String number) throws Exception {

		HttpGet httpGet = new HttpGet(

				"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);

		HttpClient httpClient = HttpClients.createDefault();
		HttpResponse res = httpClient.execute(httpGet);
		HttpEntity entity = res.getEntity();
		String result = EntityUtils.toString(entity, "UTF-8");
		JSONObject jsons = JSONObject.fromObject(result);
		String access_token = jsons.getString("access_token");
		return getPostUrl(access_token, number, type);
	}
	public  static String getPostUrl(String access_token,String id,String type) throws Exception {
		String url ="https://api.weixin.qq.com/wxa/getwxacode?access_token=";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("path", "/pages/index/index/index?type=" + type + "&number=" + id);//你二维码中跳向的地址
		JSONObject json = JSONObject.fromObject(map);
		String  res= doPost(url + access_token, json);
		return res;
	}
	/**
	 * post请求
	 * @param url
	 * @param json
	 * @return
	 */
	public  static String doPost(String url,JSONObject json){
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
 		String fi=Achieve.getUUIDString()+".png";
		try {
			StringEntity s = new StringEntity(json.toString());
			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");//发送json数据需要设置contentType
			post.setEntity(s);
			HttpResponse res = client.execute(post);

			if (res != null) {

				HttpEntity resEntity = res.getEntity();

				if (resEntity != null) {

					InputStream inStreams = resEntity.getContent();

					String uploadSysUrl =Global.getConfig("FILE");

					//
//                    // 判断这个文件（saveFile）是否存在
//
//                    if (!saveFile.getParentFile().exists()) {
//
//                        // 如果不存在就创建这个文件夹
//
//                        saveFile.getParentFile().mkdirs();
//
//                    }

					saveToImgByInputStream(inStreams, uploadSysUrl, fi);

				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return Global.getConfig("url")+"/image/"+fi;
	}

        /* @param instreams 二进制流

    * @param imgPath 图片的保存路径

    * @param imgName 图片的名称

    * @Return

    *      1：保存正常

    *      0：保存失败

    */

	public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){

		System.out.println(imgPath);
		System.out.println(imgName);

		int stateInt = 1;

		if(instreams != null){

			try {

				File file=new File(imgPath+imgName);//可以是任何图片格式.jpg,.png等

				FileOutputStream fos=new FileOutputStream(file);



				byte[] b = new byte[1024];

				int nRead = 0;

				while ((nRead = instreams.read(b)) != -1) {

					fos.write(b, 0, nRead);

				}

				fos.flush();

				fos.close();

			} catch (Exception e) {

				stateInt = 0;

				e.printStackTrace();

			} finally {

				try {

					instreams.close();

				} catch (IOException e) {

					// TODO Auto-generated catch block

					e.printStackTrace();

				}

			}

		}

		return stateInt;

	}

	/**
	 * 获取成功返回信息
	 *
	 * @param data 返回数据内容
	 * @param code 错误码
	 * @param msg  返回错误或成功信息
 	 * @return
	 */
	@SuppressWarnings({"unchecked", "rawtypes"})
	public Message<Object> getMessage(Object data, int code, String msg ) {

		return new Message(msg, code,   data);
	}

	public String getError(int code, String msg ) {

		return getJson(new ErrorMessage(msg, code, "error"));
	}



	/**
	 * 递归
	 *
	 * @param strJaggedArray
	 * @return
	 * @author wyh
	 */
	public String[] Exchange(String[][] strJaggedArray) {
		String[][] temp = DoExchange(strJaggedArray);
		return temp[0];
	}

	/**
	 * 递归
	 *
	 * @param strJaggedArray
	 * @return
	 * @author wyh
	 */
	private String[][] DoExchange(String[][] strJaggedArray) {
		int len = strJaggedArray.length;
		if (len >= 2) {
			int len1 = strJaggedArray[0].length;
			int len2 = strJaggedArray[1].length;
			int newlen = len1 * len2;
			String[] temp = new String[newlen];
			int Index = 0;
			for (int i = 0; i < len1; i++) {
				for (int j = 0; j < len2; j++) {
					temp[Index] = strJaggedArray[0][i] + strJaggedArray[1][j];
					Index++;
				}
			}
			String[][] newArray = new String[len - 1][];
			for (int i = 2; i < len; i++) {
				newArray[i - 1] = strJaggedArray[i];
			}
			newArray[0] = temp;
			return DoExchange(newArray);
		} else {
			return strJaggedArray;
		}
	}

	/**
	 * 获取当天0点的时间戳
	 */
	public static long getDayBegin() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 001);
		return cal.getTimeInMillis();
	}

	private String getJson(ErrorMessage errorMessage) {
		return   JSONObject.fromObject(errorMessage).toString();
	}

	/***
	 * 获取分页
	 * page 页码
	 *
	 * @param size 每页条数
	 * @return
	 */
	public Page getPage(HttpServletRequest request, int size) {
		int page = request.getParameter("page") == null ? 0 : Integer.parseInt(request.getParameter("page"));
		size = request.getParameter("size") == null ? size : Integer.parseInt(request.getParameter("size"));
		if (page == 0) {
			return new Page(page * size, size);
		}
		return new Page((page - 1) * size, size);
	}

	/***
	 * 屏蔽符号
	 */
	public static String replaceUtil(String str) {
		String replaceStr = "~`!@#￥$%…^&*（(）)-_+=|\\'\":;：；“”‘’<《>》.。,，/、?.";
		for (int i = 0; i < replaceStr.length(); i++)
			str = str.replace(replaceStr.substring(i, i + 1), "口");

		return encoding(str);
	}


	/***
	 * 屏蔽特殊字符
	 *
	 * @param src
	 * @return
	 */
	public static String encoding(String src) {
		if (src == null)
			return "";
		StringBuilder result = new StringBuilder();
		if (src != null) {
			src = src.trim();
			for (int pos = 0; pos < src.length(); pos++) {
				switch (src.charAt(pos)) {
					case '\"':
						result.append("&quot;");
						break;
					case '<':
						result.append("&lt;");
						break;
					case '>':
						result.append("&gt;");
						break;
					case '\'':
						result.append("&apos;");
						break;
					case '%':
						result.append("&pc;");
						break;
					case '_':
						result.append("&ul;");
						break;
					case '#':
						result.append("&shap;");
						break;
					case '?':
						result.append("&ques;");
						break;
					default:
						result.append(src.charAt(pos));
						break;
				}
			}
		}
		return result.toString();
	}

	/**
	 * 随机生成验证码
	 *
	 * @return
	 */

	public String getVerificationCodeId() {

		Random random = new Random();
		return String.valueOf(random.nextInt(89999) + 10000);
	}


	/***
	 * 随机生成26字母
	 *
	 * @return
	 */
	public String getLetter() {
		String[] str = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
				"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
				"x", "y", "z"};
		Random random = new Random();
		return str[random.nextInt(str.length - 1)];
	}

	/**
	 * 获取ID
	 *
	 * @return
	 */
	public static String getUUIDString() {
		String id = UUID.randomUUID().toString();
		id = id.replace("-", "");
		return id;
	}

	/**
	 * 拆分数据
	 *
	 * @param str
	 * @return
	 */
	public static List<String> getList(String str) {
		List listString = new ArrayList();
		for (String s : Arrays.asList(str.replace("[", "").replace("]", "")
				.split(","))) {
			listString.add(s.trim());
		}
		return listString;
	}

	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url   发送请求的URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		System.out.println(result);
		return result;
	}

	/**
	 * 发送POST请求
	 */
	public static String sendPost(String url, String param) {

		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;

			}

		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		System.out.println(result);
		return result;
	}



	public Boolean getStringBoolean(String user) {
		if (user == null) {
			return Boolean.valueOf(true);
		}
		return Boolean.valueOf(false);
	}

 
	
	//使金额==0.00
	public static double getPrice(double price) {
		return Double.valueOf(Double.parseDouble(new DecimalFormat("#.00")
				.format(price)));
	}
 


}
